//
//  NSString+TL_NSString.m
//  WXReader
//
//  Created by Andrew on 2019/4/5.
//  Copyright © 2019 Andrew. All rights reserved.
//

#import "NSString+TL_NSString.h"

@implementation NSString (TL_NSString)

- (NSString *)fileSize
{
    // 总大小
    unsigned long long size = 0;
    NSString *sizeText = @"";
    // 文件管理者
    NSFileManager *mgr = [NSFileManager defaultManager];
    
    // 文件属性
    NSDictionary *attrs = [mgr attributesOfItemAtPath:self error:nil];
    // 如果这个文件或者文件夹不存在,或者路径不正确直接返回0;
    if (attrs == nil) return @"";
    if ([attrs.fileType isEqualToString:NSFileTypeDirectory]) { // 如果是文件夹
        // 获得文件夹的大小  == 获得文件夹中所有文件的总大小
        NSDirectoryEnumerator *enumerator = [mgr enumeratorAtPath:self];
        for (NSString *subpath in enumerator) {
            // 全路径
            NSString *fullSubpath = [self stringByAppendingPathComponent:subpath];
            // 累加文件大小
            size += [mgr attributesOfItemAtPath:fullSubpath error:nil].fileSize;
            
            if (size >= pow(10, 9)) { // size >= 1GB
                sizeText = [NSString stringWithFormat:@"%.2fGB", size / pow(10, 9)];
            } else if (size >= pow(10, 6)) { // 1GB > size >= 1MB
                sizeText = [NSString stringWithFormat:@"%.2fMB", size / pow(10, 6)];
            } else if (size >= pow(10, 3)) { // 1MB > size >= 1KB
                sizeText = [NSString stringWithFormat:@"%.2fKB", size / pow(10, 3)];
            } else { // 1KB > size
                sizeText = [NSString stringWithFormat:@"%zdB", (long)size];
            }
            
        }
        return sizeText;
    } else { // 如果是文件
        size = attrs.fileSize;
        if (size >= pow(10, 9)) { // size >= 1GB
            sizeText = [NSString stringWithFormat:@"%.2fGB", size / pow(10, 9)];
        } else if (size >= pow(10, 6)) { // 1GB > size >= 1MB
            sizeText = [NSString stringWithFormat:@"%.2fMB", size / pow(10, 6)];
        } else if (size >= pow(10, 3)) { // 1MB > size >= 1KB
            sizeText = [NSString stringWithFormat:@"%.2fKB", size / pow(10, 3)];
        } else { // 1KB > size
            sizeText = [NSString stringWithFormat:@"%zdB", (long)size];
        }
        
    }
    return sizeText;
}

- (NSString *)safe_substringWithRange:(NSRange)range
{
    if (range.location > self.length) {
        return @"";
    }
    
    if (range.length > self.length) {
        return @"";
    }
    
    if ((range.location + range.length) > self.length) {
        return @"";
    }
    return [self substringWithRange:range];
}

- (BOOL)isChinese {
    int strlength = 0;

    char *p = (char*)[self cStringUsingEncoding:NSUnicodeStringEncoding];

    for (int i = 0; i < [self lengthOfBytesUsingEncoding:NSUnicodeStringEncoding]; i++) {
        if (*p) {
            p++;
            strlength++;
        } else {
            p++;
        }
    }
    
    return ((strlength / 2) == 1);
}

- (BOOL)isLetter {
    NSString *str = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符
    return str.length > 0;
}

- (BOOL)containChinese {
    for (int i = 0; i < [self length]; i++) {
        unichar t_char = [self characterAtIndex:i];
        if (t_char >= 0x4E00 && t_char <= 0x9FA5) {
            return YES;
        }
    }
    return NO;
}

YYCache *_cache = nil;
- (NSString *)wx_url {
    if (!_cache) {
        _cache = [YYCache cacheWithName:@"networkingURL"];
    }
    if ([_cache containsObjectForKey:self]) {
        return self;
    } else {
        BOOL status = [self containChinese];
        if (status) {
            NSString *t_url = [self stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            [_cache setObject:t_url forKey:self];
            return t_url;
        } else {
            [_cache setObject:self forKey:self];
            return self;
        }
    }
}

- (NSString *)firstCapitalized {
    NSString *firstStirng = [self substringToIndex:1];
    NSString *lastString = [self substringFromIndex:1];
    return [firstStirng.capitalizedString stringByAppendingString:lastString];
}

- (NSDictionary<NSString *, NSArray *> *)resetTextWithString {
    if (self.length == 0) return @{};
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"###.*?###" options:0 error:nil];
    NSArray *matches = [regex matchesInString:self options:0 range:NSMakeRange(0, self.length)];
    NSMutableArray<NSString *> *t_textArr = [NSMutableArray array];
    NSMutableArray<NSValue *> *t_arr = [NSMutableArray array];
    for (NSTextCheckingResult *value in [matches objectEnumerator]) {
        NSRange range = value.range;
        NSString *t_text = [[self substringWithRange:range] stringByReplacingOccurrencesOfString:@"#" withString:@""];
        t_text = [NSString stringWithFormat:@"%@", t_text];
        [t_textArr addObject:t_text];
        [t_arr addObject:[NSValue valueWithRange:range]];
    }
    NSDictionary *t_dict = [self stringByReplacingCharactersInRanges:t_arr strings:t_textArr];
    return t_dict;
}

- (NSDictionary<NSString *, NSArray *> *)stringByReplacingCharactersInRanges:(NSArray *)ranges strings:(NSArray<NSString *> *)strings {
    NSInteger __block offset = 0;
    NSString * __block t_text = self;
    NSMutableArray<NSValue *> *t_arr = [NSMutableArray array];
    [ranges enumerateObjectsUsingBlock:^(NSValue * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSRange range = obj.rangeValue;
        range.location -= offset;
        t_text = [t_text stringByReplacingCharactersInRange:range withString:strings[idx]];
        offset += range.length - strings[idx].length;
        [t_arr addObject:[NSValue valueWithRange:NSMakeRange(range.location, strings[idx].length)]];
    }];
    return @{t_text : t_arr};
}

- (NSString *)wx_urlWithString:(NSString *)string {
    if ([self containsString:@"?"]) {
        if ([self hasSuffix:@"?"]) {
            return [self stringByAppendingString:string];
        } else {
            if ([self hasSuffix:@"&"]) {
                return [self stringByAppendingString:string];
            } else {
                return [self stringByAppendingFormat:@"&%@", string];
            }
        }
    }
    
    return [self stringByAppendingFormat:@"?%@", string];
}
- (BOOL)TL_validateEmail{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}
@end
